package com.bestcem.xm.member.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.member.handler.imports.IndividualMemberImportHandler;
import com.bestcem.xm.member.handler.imports.InstitutionMemberImportHandler;
import com.bestcem.xm.member.handler.imports.InteriorMemberImportHandler;
import com.bestcem.xm.member.handler.imports.ProjectImportHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 示例服务
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/8/5
 */

@Slf4j
@RestController
@RequestMapping("/member/member")
public class TemplateController {

    @Resource
    private IndividualMemberImportHandler individualMemberImportHandler;

    @Resource
    private InstitutionMemberImportHandler institutionMemberImportHandler;

    @Resource
    private InteriorMemberImportHandler interiorMemberImportHandler;

    @Resource
    private ProjectImportHandler projectImportHandler;

    private final static String INDIVIDUAL_TEMPLATE = "个人联系人导入模板";

    private final static String INSTITUTION_TEMPLATE = "机构联系人导入模板";

    private final static String INTERIOR_TEMPLATE = "内部联系人导入模板";

    private final static String PROJECT_TEMPLATE = "企业项目导入模板";

    /**
     * 下载导入模板
     *
     * @param templateName
     * @param response
     * @throws IOException
     */
    @GetMapping("/template")
    public void getTemplate(@RequestParam("template_name") String templateName,
                            HttpServletResponse response,
                            HttpServletRequest request) throws IOException {
        try {
            
        String orgId = SecurityContextHolder.getOrgId();
            
         String userId = SecurityContextHolder.getUserId();
            if (log.isInfoEnabled()) {
                log.info("orgId: {}", orgId);
                log.info("userId: {}", userId);
            }
            List<Map<String, String>> head = buildExcelHeaders(templateName, orgId);
            // 添加不存在的列名并加粗
            downTemplate(templateName, response, head);
        } catch (Exception e) {
            log.error("模板下载失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    private void downTemplate(String templateName, HttpServletResponse response, List<Map<String, String>> head) throws IOException {
        String filePath;
        switch (templateName) {
            case INDIVIDUAL_TEMPLATE:
                filePath = individualMemberImportHandler.getTemplateExcelPath();
                break;
            case INSTITUTION_TEMPLATE:
                filePath = institutionMemberImportHandler.getTemplateExcelPath();
                break;
            case INTERIOR_TEMPLATE:
                filePath = interiorMemberImportHandler.getTemplateExcelPath();
                break;
            case PROJECT_TEMPLATE:
                filePath = projectImportHandler.getTemplateExcelPath();
                break;
            default:
                return;
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(templateName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ClassPathResource resource = new ClassPathResource(filePath);
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
        EasyExcel.write(response.getOutputStream())
                .withTemplate(resource.getInputStream())
                .sheet(0)
                .doFill(head, fillConfig);
    }


    private List<Map<String, String>> buildExcelHeaders(String templateName, String orgId) throws IOException {
        switch (templateName) {
            case INDIVIDUAL_TEMPLATE:
                return individualMemberImportHandler.buildExcelHeaders(orgId);
            case INSTITUTION_TEMPLATE:
                return institutionMemberImportHandler.buildExcelHeaders(orgId);
            case INTERIOR_TEMPLATE:
                return interiorMemberImportHandler.buildExcelHeaders(orgId);
            case PROJECT_TEMPLATE:
                return projectImportHandler.buildExcelHeaders(orgId);
            default:
                return new ArrayList<>();
        }
    }
}
